package com.autoagent.ai_live_master.scriptGeneration.controller;

import com.autoagent.ai_live_master.common.base.ApiResponse;
import com.autoagent.ai_live_master.common.base.UserContext;
import com.autoagent.ai_live_master.common.utils.BeanConverter;

import com.autoagent.ai_live_master.scriptGeneration.dto.CompleteScriptsGenerateDTO;
import com.autoagent.ai_live_master.scriptGeneration.dto.CompleteScriptsSaveDTO;
import com.autoagent.ai_live_master.scriptGeneration.dto.FileUploadDTO;
import com.autoagent.ai_live_master.scriptGeneration.entity.CompleteScripts;
import com.autoagent.ai_live_master.scriptGeneration.service.CompleteScriptsService;

import com.autoagent.ai_live_master.scriptGeneration.vo.CompleteScriptsGenerateVO;
import com.autoagent.ai_live_master.scriptGeneration.vo.CompleteScriptsSaveVO;
import com.autoagent.ai_live_master.scriptGeneration.vo.FileUploadVO;
import com.autoagent.ai_live_master.common.model.PageRequestVO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@Slf4j
@Tag(name = "06-完整话术管理", description = "完整话术的生成、保存和管理相关接口")
@RestController
@RequestMapping("complete-scripts")
public class CompleteScriptsController {

    @Autowired
    private CompleteScriptsService service;

    @Operation(summary = "保存完整话术内容", description = "保存用户上传的完整话术内容")
    @PostMapping(value = "/save")
    public ApiResponse<String> saveScript(
            @Parameter(description = "话术内容", required = true)
            @RequestBody CompleteScriptsSaveVO vo) {
        try {
            log.info("接收到保存话术内容请求 - 用户ID: {}", UserContext.getCurrentUserId());
            String fileName = vo.getFileName();

            // 如果不为空且不以 .md 结尾，就加上后缀
            if (fileName != null && !fileName.trim().isEmpty() && !fileName.endsWith(".md")) {
                vo.setFileName(fileName + ".md");
            }
            CompleteScriptsSaveDTO dto = BeanConverter.convert(vo, CompleteScriptsSaveDTO.class);
            dto.setUserId(UserContext.getCurrentUserId());
            
            service.saveScript(dto);
            log.info("话术内容保存成功");
            
            return ApiResponse.success("话术内容保存成功");
        } catch (Exception e) {
            log.error("话术内容保存失败 - 错误信息: {}", e.getMessage(), e);
            return ApiResponse.error(404, "话术内容保存失败");
        }
    }

    @Operation(summary = "上传话术文件", description = "上传话术文件并进行处理")
    @PostMapping(value = "/upload", consumes = "multipart/form-data")
    public ApiResponse<String> addScript(
            @Parameter(description = "上传文件信息", required = true)
            @ModelAttribute FileUploadVO vo) {
        try {
            String originalFilename = vo.getFile().getOriginalFilename();
            String title = vo.getTitle();

            // 提取后缀（包括点）
            String suffix = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            if (title == null || title.trim().isEmpty()) {
                vo.setTitle(originalFilename); // 为空，直接用原始文件名
            } else {
                vo.setTitle(title + suffix);   // 不为空，加上后缀
            }
            log.info("接收到文件上传请求 - 标题: {}, 文件名: {}", vo.getTitle(), originalFilename);

            FileUploadDTO dto = BeanConverter.convert(vo, FileUploadDTO.class);
            dto.setUserId(UserContext.getCurrentUserId());
            
            try {
                dto.setFileContent(vo.getFile().getBytes());
            } catch (IOException e) {
                log.error("读取文件内容失败", e);
                return ApiResponse.error(404, "读取文件内容失败");
            }
            
            service.addScript(dto);
            return ApiResponse.success("话术内容上传成功");
        } catch (Exception e) {
            log.error("话术内容上传失败 {}", e.getMessage(), e);
            return ApiResponse.error(404, "话术内容上传失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取话术列表", description = "分页获取用户的话术列表，支持按标题模糊搜索")
    @GetMapping("/list")
    public ApiResponse<Page<CompleteScripts>> getScripts(@ModelAttribute PageRequestVO pageRequest) {
        Long userId = UserContext.getCurrentUserId();
        log.info("获取话术列表 - 用户ID: {}, 页码: {}, 每页大小: {}, 关键字: {}",
                userId, pageRequest.getPageNum(), pageRequest.getPageSize(), pageRequest.getKeyword());
        return service.getScriptsByUserId(userId, pageRequest.getPageNum(), pageRequest.getPageSize(), pageRequest.getKeyword());
    }

    @Operation(summary = "生成完整话术", description = "根据输入生成完整的直播话术")
    @PostMapping(value = "/generate")
    public ApiResponse<String> generateCompleteScript(
            @Parameter(description = "生成参数", required = true)
            @RequestBody CompleteScriptsGenerateVO vo) {
        try {
            log.info("接收到生成完整话术请求 - 用户ID: {}", UserContext.getCurrentUserId());

            CompleteScriptsGenerateDTO dto = BeanConverter.convert(vo, CompleteScriptsGenerateDTO.class);
            dto.setUserId(UserContext.getCurrentUserId());

            String result = service.generateCompleteScript(dto);
            log.info("完整话术生成成功，结果长度: {}", result.length());

            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("生成完整话术失败 - 错误信息: {}", e.getMessage(), e);
            return ApiResponse.error(404,"生成完整话术失败");
        }
    }

    @Operation(summary = "根据ID获取话术", description = "根据话术ID获取完整的话术内容")
    @GetMapping("/{id}")
    public ApiResponse<CompleteScripts> getScriptById(
            @Parameter(description = "话术ID", required = true)
            @PathVariable Long id) {
        try {
            log.info("接收到获取话术请求 - 话术ID: {}, 用户ID: {}", id, UserContext.getCurrentUserId());
            
            CompleteScripts script = service.getScriptById(id);
            if (script == null) {
                log.warn("未找到指定的话术 - 话术ID: {}", id);
                return ApiResponse.error(404, "未找到指定的话术");
            }
            
            // 验证当前用户是否有权限访问该话术
            if (!script.getUserId().equals(UserContext.getCurrentUserId())) {
                log.warn("用户无权访问该话术 - 话术ID: {}, 用户ID: {}", id, UserContext.getCurrentUserId());
                return ApiResponse.error(403, "无权访问该话术");
            }
            
            log.info("成功获取话术内容 - 话术ID: {}", id);
            return ApiResponse.success(script);
        } catch (Exception e) {
            log.error("获取话术失败 - 话术ID: {}, 错误信息: {}", id, e.getMessage(), e);
            return ApiResponse.error(500, "获取话术失败");
        }
    }

    @Operation(summary = "修改话术", description = "修改指定ID的话术内容")
    @PutMapping("/{id}")
    public ApiResponse<CompleteScripts> updateScript(
            @Parameter(description = "话术ID", required = true)
            @PathVariable Long id,
            @Parameter(description = "话术内容", required = true)
            @RequestBody CompleteScriptsSaveVO vo) {
        try {
            log.info("接收到修改话术请求 - 话术ID: {}, 用户ID: {}", id, UserContext.getCurrentUserId());
            
            // 先获取原话术内容
            CompleteScripts existingScript = service.getScriptById(id);
            if (existingScript == null) {
                log.warn("未找到指定的话术 - 话术ID: {}", id);
                return ApiResponse.error(404, "未找到指定的话术");
            }
            
            // 验证当前用户是否有权限修改该话术
            if (!existingScript.getUserId().equals(UserContext.getCurrentUserId())) {
                log.warn("用户无权修改该话术 - 话术ID: {}, 用户ID: {}", id, UserContext.getCurrentUserId());
                return ApiResponse.error(403, "无权修改该话术");
            }
            
            // 转换并更新话术内容
            CompleteScriptsSaveDTO dto = BeanConverter.convert(vo, CompleteScriptsSaveDTO.class);
            dto.setUserId(UserContext.getCurrentUserId());
            dto.setId(id);
            
            CompleteScripts updatedScript = service.updateScript(dto);
            log.info("话术修改成功 - 话术ID: {}", id);
            
            return ApiResponse.success(updatedScript);
        } catch (Exception e) {
            log.error("修改话术失败 - 话术ID: {}, 错误信息: {}", id, e.getMessage(), e);
            return ApiResponse.error(500, "修改话术失败");
        }
    }

    @Operation(summary = "删除话术", description = "删除指定ID的话术")
    @DeleteMapping("/{id}")
    public ApiResponse<String> deleteScript(
            @Parameter(description = "话术ID", required = true)
            @PathVariable Long id) {
        try {
            log.info("接收到删除话术请求 - 话术ID: {}, 用户ID: {}", id, UserContext.getCurrentUserId());
            
            // 先获取原话术内容
            CompleteScripts existingScript = service.getScriptById(id);
            if (existingScript == null) {
                log.warn("未找到指定的话术 - 话术ID: {}", id);
                return ApiResponse.error(404, "未找到指定的话术");
            }
            
            // 验证当前用户是否有权限删除该话术
            if (!existingScript.getUserId().equals(UserContext.getCurrentUserId())) {
                log.warn("用户无权删除该话术 - 话术ID: {}, 用户ID: {}", id, UserContext.getCurrentUserId());
                return ApiResponse.error(403, "无权删除该话术");
            }
            
            service.deleteScript(id);
            log.info("话术删除成功 - 话术ID: {}", id);
            
            return ApiResponse.success("话术删除成功");
        } catch (Exception e) {
            log.error("删除话术失败 - 话术ID: {}, 错误信息: {}", id, e.getMessage(), e);
            return ApiResponse.error(500, "删除话术失败");
        }
    }
}